package com.alibaba.citrus.cr.platform.enhance.functions.diff.common.dataParser;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.alibaba.citrus.cr.platform.enhance.repository.model.diff.common.FieldLineDTO;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

/**
 * @author: qiaojiange
 * @create: 2022/01/18
 * @Description 数据转换管理器
 */
@Component
public class DataParserManager implements BeanPostProcessor {


    private Map<String, DataParser> dataParserMap = new HashedMap();

    /**
     * 数据转换器
     */
    @Resource
    private List<DataParser> dataParserList;

    /**
     * 数据转换
     *
     * @param obj 参数
     * @return 抽出出来的数据
     */
    public Map<String, FieldLineDTO> parse(Object obj) {
        Map<String, FieldLineDTO> map = new HashMap<>();
        if (obj == null) {
            return map;
        }
        DataParser dataParser = dataParserMap.get(obj.getClass().getSimpleName());
        return dataParser.parse(obj);
    }

    /**
     * 后置处理加载数据转换器
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (CollectionUtils.isNotEmpty(dataParserList)) {
            dataParserList.forEach(e -> {
                dataParserMap.put(e.obtainProcessType(), e);
            });
        }
        return bean;
    }
}
